import qs from 'qs';
import Vue from 'vue';
import axios from 'axios';
import config from './config';
import cookie from 'vue-cookies';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css'

const CancelToken = axios.CancelToken;
let cancel;

export const home_url = {
    'BaseApi': config.BaseAPI,
    "BaseApi1": config.BaseAPI1,     //基础API路径
    "BaseApi2": config.BaseAPI2,     //基础API路径
    "BaseApi3": config.BaseAPI3,     //基础API路径
};

export const apiRoot = function (path, serverType = 'BaseApi') {
    return `${home_url[serverType]}${path}`;
};

//头部存储token信息
export const getHeader = () => {
    let obj = Object();
    Reflect.set(obj, 'Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    const tokenInfo = cookie.get('tokenInfo') || {};
    if (tokenInfo.hasOwnProperty('token')) {
        Reflect.set(obj, 'token', tokenInfo.token);
    }
    return obj
};

//设置请求参数-固定参数
export const setParams = (params = {}) => {
    let userInfo = localStorage.getItem('userInfo');
    if (!!userInfo) {
        Reflect.set(params, 'userInfo', userInfo);
    }
    return params
};

export const ajaxGetJson = (path, params, serverType, infoState = 1) => {
    NProgress.start();
    return new Promise((resolve, reject) => {
        axios({
            method: 'GET',
            headers: getHeader(),
            url: apiRoot(path, serverType),
            data: setParams(params),
            cancelToken: new CancelToken(function executor(c) {
                cancel = c
            }),
        }).then((resp) => {
            // 浏览器请求成功-接口并非一定成功
            let data = successInfo(resp,infoState)
            resolve(data);
        }).catch((err) => {
            const errInfo = failInfo(err,infoState);
            reject(errInfo)
        }).finally(() => {
            NProgress.done()
        })
    });
};

export const ajaxPostJson = (path, params, serverType, infoState = 1) => {
    NProgress.start();
    return new Promise((resolve, reject) => {
        axios({
            method: "POST",
            headers: getHeader(),
            url: apiRoot(path, serverType),
            data: setParams(params),
            cancelToken: new CancelToken(function executor(c) {
                cancel = c;
            })
        }).then((resp) => {
            // 浏览器请求成功-接口并非一定成功
            let data = successInfo(resp,infoState)
            resolve(data);
        }).catch((err) => {
            const errInfo = failInfo(err,infoState);
            reject(errInfo)
        }).finally(() => {
            NProgress.done()
        })
    })
};

export const ajaxDeleteJson = (path, params, serverType) => {
    return axios({
        method: 'delete',
        contentType: "application/json; charset=utf-8",
        headers: getHeader(),
        url: apiRoot(path, serverType),
        data: params,
    })
};

export const ajaxPutJson = (path, params, serverType) => {
    return axios({
        method: "put",
        contentType: "application/json; charset=utf-8",
        headers: getHeader(),
        url: apiRoot(path, serverType),
        data: params
    })
};

export const cancelPending = () => {
    cancel('用户取消操作.');
};

export const ajaxGetForm = (path, params, serverType) => {
    return axios({
        method: "GET",
        contentType: 'application/x-www-form-urlencoded',
        headers: getHeader(),
        url: apiRoot(path, serverType),
        data: JSON.stringify(params)
    })
};

export const ajaxPostForm = (path, params, serverType) => {
    return axios({
        method: "POST",
        contentType: 'application/x-www-form-urlencoded',
        headers: getHeader(),
        url: apiRoot(path, serverType),
        data: qs.stringify(params),
    })
};

export const ajaxUploadImg = (path, file, serverType) => {
    return axios({
        method: "POST",
        contentType: false,
        processData: false,
        headers: getHeader(),
        url: apiRoot(path, serverType),
        data: file
    })
};

export const ajaxLogin = (path, params, serverType) => {
    return axios({
        method: "GET",
        url: apiRoot(path, serverType),
        data: params
    })
};

//防抖
export const debounceFn = (fn, delay) => {
    let timer = null;
    return function () {
        if (timer) {
            clearTimeout(timer)
        }
        let args = arguments;
        timer = setTimeout(function () {
            fn.apply(this, args)
        }, delay)
    }
};

//节流
export const throttleFn = (fn, time) => {
    let begin = 0;
    return function () {
        let current = new Date().getTime();
        if (current - start > time) {
            fn.apply(this, arguments);
            begin = current;
        }
    }
};

// 成功的消息处理
export const successInfo = (resp, infoState) => {
    // 浏览器状态码
    Reflect.set(resp.data, 'code', (resp.status));
    Reflect.set(resp.data, 'success', (parseInt(resp.data.status) === 0));
    let data = (resp.data);
    if (!(data.success) && !!infoState) {
        if ((data.code) !== 200) {
            Vue.prototype.$message({
                type: 'error',
                duration: 2500,
                message: '获取数据异常',
            });
        } else {
            throw new Error('网络错误或服务器错误');
        }
    }
    return data
}
// 失败消息处理
export const failInfo = (resp, infoState) => {
    const errInfo = Object();
    if (!!resp.response) {
        const {status, headers, data} = resp.response;
        Reflect.set(errInfo, 'status', status);
        Reflect.set(errInfo, 'headers', headers);
        Reflect.set(errInfo, 'data', data);
    }
    if (!!infoState) {
        Vue.prototype.$message({
            type: 'error',
            duration: 2500,
            message: '网络错误或服务器错误',
        });
    }
    console.log('failInfo')
    return errInfo
}